package com.yuji.aacar.core.mvvm.appbase;

import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;

import com.yuji.aacar.core.cores.excep.ExceptionController;
import com.yuji.aacar.core.cores.utils.LogUtil;
import com.yuji.aacar.core.mvvm.apptask.TaskManager;
import com.yuji.aacar.core.mvvm.apptask.TaskToken;
import com.yuji.aacar.core.mvvm.apptask.ViewModelManager;

import java.util.HashMap;

import okhttp3.Route;


/**
 * <li>Description:
 * <br> 该类用于进行activity的切换，总共定义了两种切换方式</br>
 * <br> 1.不包含网络请求的切换,仅是封装了普通的Intent跳转方式</br>
 * <br> 2.包含网络请求的切换,在Intent跳转的同时，另起线程进行网络请求</br>
 * </li>
 */

public class AppRoute {

    public static String ACTIVITY_TOKEN_KEY = "activity_token_key";
    private static AppRoute sRoute;
    public static int WITHOUT_RESULTCODE = -1;

    public static AppRoute getInstance() {
        synchronized (Route.class) {
            if (sRoute == null) {
                sRoute = new AppRoute();
                //TODO 初始化所有的serviceMediator方法和参数
            }
            return sRoute;
        }
    }

    private ExceptionController controller;

    /**
     * 跳转到下一个activity（无网络请求）
     *
     * @param currentActivity 当前要跳的activity
     * @param nextActivity    下个activity
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     */
    public void nextController(Activity currentActivity, Class nextActivity, int resultCode) {

        String nextClassName = nextActivity.getName();
        LogUtil.e("--nextController--", "[Route][" + currentActivity.getClass().getSimpleName() + "] go to [" + nextActivity.getSimpleName() + "]");
        CoreBaseViewModel nextViewModel = ViewModelManager.getInstance().newViewModel(nextClassName);
        LogUtil.e("--nextController--", "[viewModel][" + nextViewModel.getActivityClass() + "]");
        Intent intent;
        try {
            intent = new Intent(currentActivity, Class.forName(nextClassName));
            nextViewModel.showProgressBar = false;
            intent.putExtra(ACTIVITY_TOKEN_KEY, nextViewModel.getViewModelId());
            if (resultCode == WITHOUT_RESULTCODE) {
                currentActivity.startActivity(intent);
            } else {
                currentActivity.startActivityForResult(intent, resultCode);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            LogUtil.e("activity", "[Route][nextController] catch ClassNotFoundException" + e);
        }
    }

    /**
     * 从Fragment跳转到下一个activity（无网络请求）
     *
     * @param currentFragment 当前要跳的Fragment
     * @param nextActivity    下个activity
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     */
    public void nextControllerForFragment(Fragment currentFragment, Class nextActivity, int resultCode) {

        String nextClassName = nextActivity.getName();
        LogUtil.e("--nextController--", "[Route][" + currentFragment.getClass().getSimpleName() + "] go to [" + nextActivity.getSimpleName() + "]");
        CoreBaseViewModel nextViewModel = ViewModelManager.getInstance().newViewModel(nextClassName);
        LogUtil.e("--nextController--", "[viewModel][" + nextViewModel.getActivityClass() + "]");
        Intent intent;
        try {
            intent = new Intent(currentFragment.getActivity(), Class.forName(nextClassName));
            nextViewModel.showProgressBar = false;
            intent.putExtra(ACTIVITY_TOKEN_KEY, nextViewModel.getViewModelId());
            if (resultCode == WITHOUT_RESULTCODE) {
                currentFragment.startActivity(intent);
            } else {
                currentFragment.startActivityForResult(intent, resultCode);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            LogUtil.e("activity", "[Route][nextController] catch ClassNotFoundException" + e);
        }
    }


    /**
     * 跳转到下一个activity（带网络请求）
     *
     * @param currentActivity 待创建的activity相应的viewmodel
     * @param nextClass       跳转的类
     * @param methodName      请求方法
     * @param params          请求参数
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     */
    public void nextController(Activity currentActivity, Class nextClass, String methodName, HashMap<String,Object> params,
                               int resultCode) {

        CoreBaseViewModel viewModel = ViewModelManager.getInstance().newViewModel(nextClass.getName());
        viewModel.requestMethodName = methodName;
        LogUtil.e("activity", "[Route][" + currentActivity.getClass().getSimpleName() + "] go to [" + nextClass + "]");
        try {
            if (methodName != null) {
                TaskToken token = TaskManager.getInstance().doTask(viewModel,
                        methodName,params);
                viewModel.setTaskToken(token);
                viewModel.showProgressBar = true;
            }
            Intent intent = new Intent(currentActivity, Class.forName(nextClass.getName()));
            intent.putExtra(ACTIVITY_TOKEN_KEY, viewModel.getViewModelId());
            if (resultCode == WITHOUT_RESULTCODE) {
                currentActivity.startActivity(intent);
            } else {
                currentActivity.startActivityForResult(intent, resultCode);
            }
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
            LogUtil.e("activity", "[Route] [" + nextClass + "] catch ClassNotFoundException" + e1);
        }
    }


    /**
     * 从Fragment跳转到下一个activity（带网络请求）
     *
     * @param currentFragment 待创建的activity相应的viewmodel
     * @param nextClass       跳转的类
     * @param methodName      请求方法
     * @param params          请求参数
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     */
    public void nextControllerForFragment(Fragment currentFragment, Class nextClass, String methodName, HashMap<String,Object> params,
                               int resultCode) {

        CoreBaseViewModel viewModel = ViewModelManager.getInstance().newViewModel(nextClass.getName());
        viewModel.requestMethodName = methodName;
        LogUtil.e("activity", "[Route][" + currentFragment.getClass().getSimpleName() + "] go to [" + nextClass + "]");
        try {
            if (methodName != null) {
                TaskToken token = TaskManager.getInstance().doTask(viewModel,
                        methodName,params);
                viewModel.setTaskToken(token);
                viewModel.showProgressBar = true;
            }
            Intent intent = new Intent(currentFragment.getActivity(), Class.forName(nextClass.getName()));
            intent.putExtra(ACTIVITY_TOKEN_KEY, viewModel.getViewModelId());
            if (resultCode == WITHOUT_RESULTCODE) {
                currentFragment.startActivity(intent);
            } else {
                currentFragment.startActivityForResult(intent, resultCode);
            }
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
            LogUtil.e("activity", "[Route] [" + nextClass + "] catch ClassNotFoundException" + e1);
        }
    }


    /**
     * 跳转到下一个activity（无网络请求）<br>
     * 只有在intent需要设置特殊参数时 适用
     *
     * @param currentActivity 当前的activity
     * @param nextActivity    待创建的activity相应的viewmodel
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     * @param intent          跳转的intent
     */
    public void nextControllerWithIntent(Activity currentActivity, Class nextActivity, int resultCode, Intent intent) {
        //        XLog.instance().log("activity").debug("[Route][" + currentActivity.getClass().getSimpleName() + "] go to [" + nextClassName + "]");

        String nextClassName = nextActivity.getName();
        LogUtil.e("--nextController--", "[Route][" + currentActivity.getClass().getSimpleName() + "] go to [" + nextActivity.getSimpleName() + "]");
        CoreBaseViewModel nextViewModel = ViewModelManager.getInstance().newViewModel(
                nextClassName);
        LogUtil.e("--nextController--", "[viewModel][" + nextViewModel.getActivityClass() + "]");
        nextViewModel.showProgressBar = false;
        intent.setClass(currentActivity, nextActivity);
        intent.putExtra(ACTIVITY_TOKEN_KEY, nextViewModel.getViewModelId());
        if (resultCode == WITHOUT_RESULTCODE) {
            currentActivity.startActivity(intent);
        } else {
            currentActivity.startActivityForResult(intent, resultCode);
        }
    }

    /**
     * 从一个fragment跳转到下一个activity（无网络请求）<br>
     * 只有在intent需要设置特殊参数时 适用
     *
     * @param currentFragment 当前的Fragment
     * @param nextActivity    待创建的activity相应的viewmodel
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     * @param intent          跳转的intent
     */
    public void nextControllerForFragmentWithIntent(Fragment currentFragment, Class nextActivity, int resultCode, Intent intent) {
        String nextClassName = nextActivity.getName();
        LogUtil.e("--nextController--", "[Route][" + currentFragment.getClass().getSimpleName() + "] go to [" + nextActivity.getSimpleName() + "]");
        CoreBaseViewModel nextViewModel = ViewModelManager.getInstance().newViewModel(
                nextClassName);
        LogUtil.e("--nextController--", "[viewModel][" + nextViewModel.getActivityClass() + "]");
        nextViewModel.showProgressBar = false;
        intent.setClass(currentFragment.getActivity(), nextActivity);
        intent.putExtra(ACTIVITY_TOKEN_KEY, nextViewModel.getViewModelId());
        if (resultCode == WITHOUT_RESULTCODE) {
            currentFragment.startActivity(intent);
        } else {
            currentFragment.startActivityForResult(intent, resultCode);
        }


    }


    /**
     * 跳转到下一个activity（带网络请求）<br>
     * 只有在intent需要设置特殊参数时 适用
     *
     * @param currentActivity 待创建的activity相应的viewmodel
     * @param nextClass       跳转的类
     * @param methodName      请求方法
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     * @param intent          intent对象
     */
    public void nextControllerWithIntent(Activity currentActivity, Class nextClass, String methodName,HashMap<String,Object> params,
                                         int resultCode, Intent intent) {

        CoreBaseViewModel viewModel = ViewModelManager.getInstance().newViewModel(nextClass.getName());
        //        viewModel.baseRequest = request;
        LogUtil.e("activity", "[Route][" + currentActivity.getClass().getSimpleName() + "] go to [" + nextClass + "]");
        if (methodName != null) {
            TaskToken token = TaskManager.getInstance().doTask(viewModel,
                    methodName, params);
            viewModel.setTaskToken(token);
            viewModel.showProgressBar = true;
        }
        intent.setClass(currentActivity, nextClass);
        intent.putExtra(ACTIVITY_TOKEN_KEY, viewModel.getViewModelId());
        if (resultCode == WITHOUT_RESULTCODE) {
            currentActivity.startActivity(intent);
        } else {
            currentActivity.startActivityForResult(intent, resultCode);
        }
    }

    /**
     * 从一个fragment跳转到下一个activity（带网络请求）<br>
     * 只有在intent需要设置特殊参数时 适用
     *
     * @param currentFragment 待创建的Fragment相应的viewmodel
     * @param nextClass       跳转的类
     * @param methodName      请求方法
     * @param resultCode      是否关心返回，默认为 WITHOUT_RESULTCODE = -1
     * @param intent          intent对象
     */
    public void nextControllerForFragmentWithIntent(Fragment currentFragment, Class nextClass, String methodName,HashMap<String,Object> params,
                                         int resultCode, Intent intent) {

        CoreBaseViewModel viewModel = ViewModelManager.getInstance().newViewModel(nextClass.getName());
        //        viewModel.baseRequest = request;
        LogUtil.e("activity", "[Route][" + currentFragment.getClass().getSimpleName() + "] go to [" + nextClass + "]");
        if (methodName != null) {
            TaskToken token = TaskManager.getInstance().doTask(viewModel,
                    methodName, params);
            viewModel.setTaskToken(token);
            viewModel.showProgressBar = true;
        }
        intent.setClass(currentFragment.getActivity(), nextClass);
        intent.putExtra(ACTIVITY_TOKEN_KEY, viewModel.getViewModelId());
        if (resultCode == WITHOUT_RESULTCODE) {
            currentFragment.startActivity(intent);
        } else {
            currentFragment.startActivityForResult(intent, resultCode);
        }
    }


}
